package day05;

import java.io.PrintWriter;
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Demo09 {
    /*
     * 利用队列异步写文件
     */
    public static void main(String[] args) {
        BlockingQueue<String> queue = new LinkedBlockingQueue<>(10);
        Thread t1 = new Thread(){
            @Override
            public void run() {
                //从控制台读取信息, 插入到队列
                Scanner scanner = new Scanner(System.in);
                while (true){
                    String str = scanner.nextLine();
                    try {
                        queue.put(str);
                        if("quit".equals(str)){
                            break;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        t1.start();
        Thread t2 = new Thread(){
            @Override
            public void run() {

                //从队列中读取信息, 写到文件
                try (PrintWriter out = new PrintWriter(
                        "demo.txt","UTF-8");){
                    while (true){
                        String str = queue.take();
                        out.println(str);
                        System.out.println("写入:"+str);
                        out.flush();
                        if ("quit".equals(str)){
                            break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        };
        t2.setDaemon(true);
        t2.start();
    }
}
